package com.ruoyi.feike.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.ruoyi.activiti.domain.dto.ActTaskDTO;
import com.ruoyi.activiti.domain.vo.SearchVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.dto.WaitForSaveNoteDTO;
import com.ruoyi.feike.domain.dto.YearAuditSaveDTO;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.domain.vo.AnnualReviewyVO;
import com.ruoyi.feike.domain.vo.ApprovalStatusVO;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.service.ISysPostService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.xmlgraphics.util.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * feikeController
 *
 * @author ruoyi
 * @date 2022-07-07
 */
@Api(value = "年审发起流程页",tags = "年审表类信息展示回显",description = "年审列表下面用")
@RestController
@RequestMapping("/feike/annual_review")
public class AnnualReviewyController extends BaseController {
    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${wfs.url}")
    private String wfsUrl;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private HBasicCorporateGuaranteeMapper basicCorporateGuaranteeMapper;

    @Autowired
    private HBasicCorporateMapper basicCorporateMapper;


    @Autowired
    private HAmlMapper amlMapper;


    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;


    @Autowired
    private HDealerDmMapper hDealerDmMapper;

    /**
     * 查询feike带任务列表列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/annual_review")
    public TableDataInfo list(AnnualReviewy annualReviewy) {
        startPage();
        List<AnnualReviewy> list = annualReviewyService.selectAnnualReviewyAndTaskNameList(annualReviewy);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/lists")
    public TableDataInfo listById(AnnualReviewy annualReviewy) {
        startPage();
        List<AnnualReviewyVO> list = annualReviewyService.selectAnnualReviewyVOList(annualReviewy);
        return getDataTable(list);
    }

    /**
     * 查询feike列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/listAll")
    public TableDataInfo listAll(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
/*        Boolean isFlag = false;

        if(StringUtils.isNotEmpty(annualReviewy.getOrderByColumn()) && annualReviewy.getOrderByColumn().equalsIgnoreCase("dealerName")){
            isFlag =true;
            annualReviewy.setOrderByColumn("");
        }*/


        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(loginUser.getUser().getUserName().equals("Support") ||  loginUser.getUser().getUserName().equals("Support1")  || loginUser.getUser().getUserName().contains("Support")){
            //说明是DM超级账号,需要查询所有DM代办
            startPageOrderNull();
            List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList3(annualReviewy,basicInformation);
            return getDataTable(dataProcessing(list));
        }

        List<Integer> integers = postService.selectPostListByUserId(loginUser.getUser().getUserId());
        if(integers.contains(9) && !loginUser.getUser().getUserName().equals("ry2") ) {
            annualReviewy.setUwFlag("1");
        }
        //UW历史
        if(annualReviewy.getIsHis()!=null && annualReviewy.getIsHis().equals("1")){
            startPageOrderNull();
            List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList1(annualReviewy,basicInformation);
            return getDataTable(dataProcessing(list));
        }
        //OP历史
        if(annualReviewy.getIsHis()!=null && annualReviewy.getIsHis().equals("2")){
            startPageOrderNull();
            List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList2(annualReviewy,basicInformation);
            return getDataTable(dataProcessing(list));
        }
        if(integers.contains(5)) {
            annualReviewy.setIsFlag("1");
        }
        startPageOrderNull();
        List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList(annualReviewy,basicInformation);
        return getDataTable(dataProcessing(list));
    }

    public List<AnnualReviewyHistoryVO> dataProcessing(List<AnnualReviewyHistoryVO> list){
        for (AnnualReviewyHistoryVO annualReviewyHistoryVO : list) {

            if(StringUtils.isNotEmpty(annualReviewyHistoryVO.getDealerName())){
                String[] split = annualReviewyHistoryVO.getDealerName().split(",");
                Set<String> setString =new HashSet<>();
                for (String dealerName : split) {
                    if(StringUtils.isNotEmpty(dealerName)){
                        HDealerDm hDealerDm = hDealerDmMapper.selectHDealerDmByDealerName(dealerName);
                        if(hDealerDm!=null && StringUtils.isNotEmpty(hDealerDm.getUwName())){
                            setString.add(hDealerDm.getUwName());
                        }
                    }
                }
                if(setString.size()>0){
                    String join = StringUtils.join(setString, ",");
                    annualReviewyHistoryVO.setUw(join);
                }
            }
            //查询
            if(StringUtils.isNotEmpty(annualReviewyHistoryVO.getInstanceId()) && annualReviewyHistoryVO.getInstanceId().contains("WLS")){
                AnnualReviewy annualReviewy1 = annualReviewyMapper.selectAnnualReviewyByInstanceId1(annualReviewyHistoryVO.getInstanceId());
                if(annualReviewy1 != null && StringUtils.isNotEmpty(annualReviewy1.getUwApprovalName())){
                    annualReviewyHistoryVO.setUw(annualReviewy1.getUwApprovalName());
                }
            }
        }

        return list;
    }

    //TODO
    /**
     * 导出feike列表
     */
    @PreAuthorize("@ss.hasPermi('feike:feike:export')")
    @Log(title = "feike", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        List<AnnualReviewyHistoryVO> list = annualReviewyService.selectAnnualReviewyList(annualReviewy,basicInformation);
        ExcelUtil<AnnualReviewyHistoryVO> util = new ExcelUtil<AnnualReviewyHistoryVO>(AnnualReviewyHistoryVO.class);
        return util.exportExcel(list, "feike");
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(annualReviewyService.selectAnnualReviewyById(id));
    }

    /**
     * 获取feike详细信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @GetMapping(value = "/ByInstanceId/{instanceId}")
    public AjaxResult getInfoByInstanceId(@PathVariable("instanceId") String instanceId) {
        try {
            if(!StringUtils.isEmpty(instanceId)){
                String id = instanceId.replace("\"", "");
                return AjaxResult.success(annualReviewyService.selectAnnualReviewyByInstanceId(id));
            }else{
                return AjaxResult.success();
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("数据异常,请联系管理员");
        }
    }

    @GetMapping(value = "/getCorporateGuarantee/{instanceId}")
    public AjaxResult getCorporateGuarantee(@PathVariable("instanceId") String instanceId) {
        if(!StringUtils.isEmpty(instanceId)){
            String id = instanceId.replace("\"", "");
            return AjaxResult.success(annualReviewyService.getCorporateGuarantee(id));
        }else{
            return AjaxResult.success();
        }
    }



    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult add(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.insertAnnualReviewy(map));
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult edit(@RequestBody Map<String, Object> map) {
        System.out.println("修改=="+map);
        int i = annualReviewyService.updateAnnualReviewy(map);
        /*if(i == 500 ){
            return  AjaxResult.error("500","此流程已被锁定");
        }*/
        return toAjax(i);
    }

    /**
     * 修改feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:edit')")
    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping("/closeUpdateAnnualReviewyObj/{instanceId}")
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult closeUpdateAnnualReviewyObj(@PathVariable String instanceId) {
        String username = SecurityUtils.getLoginUser().getUsername();
        return toAjax(annualReviewyService.closeUpdateAnnualReviewyObj(instanceId,username));
    }

    @Log(title = "feike", businessType = BusinessType.UPDATE)
    @PutMapping("/openUpdateAnnualReviewyObj")
    //public AjaxResult edit(@RequestBody AnnualReviewy annualReviewy) {
    public AjaxResult openUpdateAnnualReviewyObj() {
        String username = SecurityUtils.getLoginUser().getUsername();
        annualReviewyService.openUpdateAnnualReviewyObj(username);
        return toAjax(1);
    }

    /**
     * 删除feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(annualReviewyService.deleteAnnualReviewyByIds(ids));
    }

    /**
     * 删除feike --草稿使用
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:remove')")
    @Log(title = "feike", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteById/{id}")
    public AjaxResult deleteById(@PathVariable String id) {
        return toAjax(annualReviewyService.deleteAnnualReviewyById(id));
    }

    @Log(title = "feike", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteProposalById/{id}")
    public AjaxResult deleteProposalById(@PathVariable String id) {
        return toAjax(annualReviewyMapper.deleteProposalById(id));
    }

    //TODO--待完善
    @RequestMapping("/uploads")
    public String uploadFile(MultipartFile[] files, HttpServletRequest request) {
        //String realPath = request.getServletContext().getRealPath("/img");
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

        //创建年月日文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String res = simpleDateFormat.format(new Date());
        String year = res.substring(0, 4);   //2022
        String month = res.substring(4, 6);  //07
        String day = res.substring(6);      //08
        String fileUploadPath = path + "static/FileUpload/";
        //String fileUploadPath = path + "static/FileUpload/"+File.separator+year+File.separator+month+File.separator+day+File.separator;
        File fileUploadfolder = new File(fileUploadPath);
        //判断目录是否存在，不存在则创建目录
        if (!fileUploadfolder.exists()) {
            fileUploadfolder.mkdirs();
        }
        for (MultipartFile file : files) {
            //获取上传文件的源文件名称
            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(fileUploadfolder, newName));
                //打印上传文件的url
                System.out.println(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/FileUpload/" + newName);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传文件失败";
            }
        }
        return "上传文件成功";
    }

    /**
     * 根据id查询，给邮箱模板返回需要的信息
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:query')")
    @PostMapping(value = "/mailInfo/{instanceId}")
    public AjaxResult getMailInfo(@PathVariable("instanceId") String instanceId) {
        return AjaxResult.success(annualReviewyService.selectMailInfoByInstanceId(instanceId));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/startDM")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult startDM(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.startDM(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/dmSelect")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult dmSelect(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.dmSelect(map));
    }

    /**
     * 新增feike
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:add')")
    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/startPLM")
    //public AjaxResult add(@RequestBody AnnualReviewy annualReviewy)
    public AjaxResult startPLM(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.startPLM(map));
        //@PreAuthorize("@ss.hasPermi('feike:feike:query')")
    }

    @Log(title = "feike", businessType = BusinessType.INSERT)
    @PostMapping("/updateMain")
    public AjaxResult updateMain(@RequestBody Map<String, Object> map) {
        return toAjax(annualReviewyService.updateMain(map));
    }

    @Log(title = "feike", businessType = BusinessType.DELETE)
    @PostMapping("/deleteMain")
    public AjaxResult deleteMain(@RequestBody String id) {
        return annualReviewyService.deleteMain(id);
    }

    @GetMapping("/getMain/{taskId}")
    public AjaxResult getMain(@PathVariable("taskId") String taskId) {
        return AjaxResult.success(annualReviewyService.getMain(taskId));
    }

    //条件查询--搜索按钮方法
    @GetMapping(value = "/search")
    public TableDataInfo getPageInfo( SearchVo searchVo) {
        PageDomain pageDomain = TableSupport.buildPageRequest();

        Page<ActTaskDTO> hashMaps = annualReviewyService.selectProcessDefinitionSearchList(searchVo,pageDomain);
        return getDataTable(hashMaps);

    }

    @GetMapping("/indexData")
    public ResultData indexData(){
        CustomPage hashMaps = annualReviewyService.indexData();
        return getResult(hashMaps);
    }

    /**
     * 调用第三方接口进行数据查询刷新
     * @return
     */
    @PostMapping("/threeRefresh")
    public AjaxResult getRefreshList(@RequestBody Map<String, Object> map){
        // TODO 后面甲方提供了接口，在进行调用测试，获取数据进行刷新
        String urlStr=wfsUrl+"CreditInfo";   //第三方接口路径
        // 添加请求头信息
        JSONObject jsonObject = new JSONObject();
        Map<String, String > heads = new HashMap<>();
        // 使用json发送请求，下面的是必须的
        heads.put("Content-Type", "application/json;charset=UTF-8");

        /**
         * post请求
         ** headerMap是添加的请求头，
         body是传入的参数，这里选择json，后端使用@RequestBody接收
         */
        List dealerCodeList = new ArrayList();
        // String groupName = (String) map.get("groupName");
        List dealerNameList = (List) map.get("dealerName");
        System.out.println("dealerNameList=="+dealerNameList);
        // 根据集团名称和经销商名称获取dealercode对象   "DealerCode":[["L061701","M01002"],["L061702","M01003"]]
        List<Map<String,Object>> codeList =new ArrayList();
        if(dealerNameList!=null && dealerNameList.size()>0){
            for (int i = 0; i < dealerNameList.size(); i++) {

                String str = (String) dealerNameList.get(i);
                List dealerInformationList = annualReviewyService.getInfoListByDealerName(str);
                System.out.println("dealerInformationList=="+dealerInformationList);
                if (dealerInformationList!=null && dealerInformationList.size()>0){
                    for (int j = 0; j < dealerInformationList.size(); j++) {
                        Map<String,Object> dealerAndDealerCodeMap = new HashMap<>();
                        String dealerCodeStr = (String) dealerInformationList.get(j);
                        dealerAndDealerCodeMap.put(dealerCodeStr,str);
                        codeList.add(dealerAndDealerCodeMap);
                    }
                }
                dealerCodeList.add(dealerInformationList);
            }
        }
        System.out.println("codeList=="+codeList);
        System.out.println("dealerCodeList=="+dealerCodeList);
        // String jsonString = JSON.toJSONString(dealerCodeList);
        jsonObject.put("DealerCode",dealerCodeList);

        String response = HttpRequest.post(urlStr)
                                 .header("Content-Type", "application/json;charset=UTF-8")
                                 .body(jsonObject.toString())
                                 .execute()
                                 .body();
        System.out.println("response=="+response);

        Map<String,Object> mapObj=new HashMap<>();
        List<Map<String,Object>> wholesalePerformanceCurrentlyList=new ArrayList<>();
        List<Map<String,Object>> crixpGradeLists = new ArrayList<>();

        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(response);
        Integer code1 = (Integer) entries.get("Code");
        if (code1==200){
            // String dataList = entries.get("Data").toString();
            List data = (List) entries.get("Data");
            String strObj = JSON.toJSONString(data);
            data = JSON.parseArray(strObj);
            System.out.println("data===="+data);
            if (data!=null && data.size()>0){
                for (int i = 0; i < data.size(); i++) {
                    List firstList = (List) data.get(i);    //data中的第一个数组
                    System.out.println("firstList===="+firstList);
                    if (firstList!=null && firstList.size()>0){
                        for (int i1 = 0; i1 < firstList.size(); i1++) {
                            /*List dealerNameLists = (List) map.get("dealerName");
                            if(dealerNameLists!=null && dealerNameLists.size()>0){

                            }
                            for (int x = 0; x < dealerNameList.size(); x++) {
                                List<String> list = (List<String>) dealerCodeList.get(i1);

                                if(list.get(0).equals(dealerCode)){
                                    String str = (String) dealerNameList.get(x);

                                }

                            }*/
                            Map<String,Object> firstMap = (Map<String, Object>) firstList.get(i1); //data中的第一个数组中的第一个对象
                            String dealerCode = (String) firstMap.get("DealerCode");
                            List creditInfoList = (List) firstMap.get("CreditInfo");     //CreditInfo数组
                            System.out.println("dealerCode=="+dealerCode);
                            System.out.println("creditInfoList=="+creditInfoList);
                            Map<String,Object> tempObj = new HashMap<>();
                            if (creditInfoList!=null && creditInfoList.size()>0){

                                for (int i11 = 0; i11 < creditInfoList.size(); i11++) {
                                    Map<String,Object> creditInfoListFirstMap = (Map<String, Object>) creditInfoList.get(i11);//CreditInfo数组中的第一个对象
                                    String sector = (String) creditInfoListFirstMap.get("Sector");
                                    List crixpGradeList = (List) creditInfoListFirstMap.get("CrixpGrade");  //CreditInfo数组中的第一个对象中的CrixpGrade数组
                                    System.out.println("sector=="+sector);
                                    System.out.println("crixpGradeList=="+crixpGradeList);
                                    // int currentYear = new Date().getYear();
                                    Calendar calendar = Calendar.getInstance();
                                    int currentYear = calendar.get(Calendar.YEAR);
                                    System.out.println("currentYear==22=="+currentYear);
                                    int year =0;
                                    String grade ="";
                                    int year1 =0;
                                    String grade1 ="";
                                    for (int i2 = 0; i2 < crixpGradeList.size(); i2++) {
                                        Map<String,Object> creditInfoListFirstObj = (Map<String,Object>)crixpGradeList.get(i2);
                                        Object year2 = creditInfoListFirstObj.get("Year");
                                        System.out.println("year2===="+year2);
                                        System.out.println("currentYear=="+currentYear);
                                        if(String.valueOf(creditInfoListFirstObj.get("Year")).equals(String.valueOf(""+currentYear))){
                                            year =  currentYear;
                                            grade = (String) creditInfoListFirstObj.get("Grade");
                                        }
                                        if(String.valueOf(creditInfoListFirstObj.get("Year")).equals(String.valueOf(""+(currentYear-1)))){
                                            year1 = currentYear-1;
                                            grade1 = (String) creditInfoListFirstObj.get("Grade");
                                        }
                                    }

                                    for (Map<String, Object> stringObjectMap : codeList) {
                                        boolean contains=stringObjectMap.containsKey(dealerCode);  //判断是否包含指定的键值
                                        if(contains){  //如果条件为真
                                            tempObj.put("Dealer",stringObjectMap.get(dealerCode));
                                            tempObj.put("DealerCode",dealerCode);
                                            tempObj.put("lastYear",year1);
                                            tempObj.put("thisYear",currentYear);
                                            tempObj.put("thisYearGrade",grade);
                                            tempObj.put("lastYearGrade",grade1);
                                            crixpGradeLists.add(tempObj);
                                        }
                                    }

                                    List creditDetList = (List) creditInfoListFirstMap.get("CreditDet");  //CreditInfo数组中的第一个对象中的CreditDet数组
                                    if(creditDetList!=null && creditDetList.size()>0){
                                        for (int i112 = 0; i112 <creditDetList.size() ; i112++) {
                                            WholesalePerformanceCurrently wholesalePerformanceCurrently = new WholesalePerformanceCurrently();
                                            Map<String,Object> wholesalePerformanceCurrentlyMap = new HashMap<>();
                                            Map<String,Object> creditDetListFirstObj = (Map<String, Object>) creditDetList.get(i112);
                                            String limitType = creditDetListFirstObj.get("LimitType")!=null?creditDetListFirstObj.get("LimitType").toString():"";
                                            int creditLimit = (int) creditDetListFirstObj.get("CreditLimit");     // 我们这边是Double类型，传的是Integer类型
                                            String expiryDate = creditDetListFirstObj.get("ExpiryDate")!=null?creditDetListFirstObj.get("ExpiryDate").toString():"";
                                            String securityRatio = creditDetListFirstObj.get("SecurityRatio")!=null?creditDetListFirstObj.get("SecurityRatio").toString():"";
                                            int activeLimit = (int) creditDetListFirstObj.get("ActiveLimit");   // 我们这边是Double类型，传的是Integer类型
                                            Object activeOS =  creditDetListFirstObj.get("ActiveOS")!=null?creditDetListFirstObj.get("ActiveOS"):creditDetListFirstObj.get("ActiveOS");       // 我们这边是Double类型，传的是Integer类型

                                            System.out.println("limitType=="+limitType);
                                            System.out.println("creditLimit=="+creditLimit);
                                            System.out.println("expiryDate=="+expiryDate.toString());
                                            System.out.println("securityRatio=="+securityRatio.toString());
                                            System.out.println("activeLimit=="+activeLimit);
                                            System.out.println("activeOS=="+activeOS);

                                            for (Map<String, Object> stringObjectMap : codeList) {
                                                boolean contains=stringObjectMap.containsKey(dealerCode);  //判断是否包含指定的键值
                                                if(contains){  //如果条件为真
                                                    wholesalePerformanceCurrentlyMap.put("dealername",stringObjectMap.get(dealerCode));
                                                    wholesalePerformanceCurrentlyMap.put("dealerCode",dealerCode);
                                                    wholesalePerformanceCurrentlyMap.put("sector",sector);
                                                    wholesalePerformanceCurrentlyMap.put("limitType",limitType);
                                                    wholesalePerformanceCurrentlyMap.put("creditLimit",creditLimit);
                                                    wholesalePerformanceCurrentlyMap.put("expiryDate",expiryDate);
                                                    wholesalePerformanceCurrentlyMap.put("securityRatio",securityRatio);
                                                    wholesalePerformanceCurrentlyMap.put("activeLimit",activeLimit);
                                                    wholesalePerformanceCurrentlyMap.put("activeOS",activeOS);
                                                    wholesalePerformanceCurrentlyList.add(wholesalePerformanceCurrentlyMap);
                                                }
                                            }

                                            // wholesalePerformanceCurrently.setDealername(dealerCode);
                                            // wholesalePerformanceCurrently.setde(dealerCode);
                                            // wholesalePerformanceCurrently.setSector(sector);
                                            // wholesalePerformanceCurrently.setLimitType(limitType);
                                            // wholesalePerformanceCurrently.setCreditLimit(creditLimit.longValue());
                                            // wholesalePerformanceCurrently.setActivatedLimit(activeLimit.longValue());
                                            // wholesalePerformanceCurrently.setExpiredDates(expiryDate.toString());
                                            // wholesalePerformanceCurrently.setOs(Long.valueOf(String.valueOf(activeOS)));
                                            // wholesalePerformanceCurrently.setOs(activeOS);
                                            // wholesalePerformanceCurrently.setActiveOS(""+activeOS);

                                        }
                                    }
                                }

                            }


                        }

                    }

                }

            }

            Map<String,Object> dataSummaryMap = (Map<String, Object>) entries.get("DataSummary");
            if (dataSummaryMap!=null){
                Object dataCount =  dataSummaryMap.get("DataCount");  // BigDecimal
                Object creditInfoCount =  dataSummaryMap.get("CreditInfoCount");
                Object creditDetCount =  dataSummaryMap.get("CreditDetCount");
                Object creditLimitSum =  dataSummaryMap.get("CreditLimitSum");
                Object activeLimitSum =  dataSummaryMap.get("ActiveLimitSum");
                Object activeOSSum =  dataSummaryMap.get("ActiveOSSum");

                System.out.println("dataCount=="+dataCount);
                System.out.println("creditInfoCount=="+creditInfoCount);
                System.out.println("creditDetCount=="+creditDetCount);
                System.out.println("creditLimitSum=="+creditLimitSum);
                System.out.println("activeLimitSum=="+activeLimitSum);
                System.out.println("activeOSSum=="+activeOSSum);
            }
        }
        mapObj.put("wholesalePerformanceCurrently",wholesalePerformanceCurrentlyList);
        mapObj.put("crixpGrade",crixpGradeLists);
        System.out.println("crixpGradeLists===="+crixpGradeLists);

        return AjaxResult.success(mapObj);
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        logger.info("文件上传调用开始");
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            logger.info("上传文件路径{}",filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String originalFilename = file.getOriginalFilename();       // 文件的中文名
            logger.info("fileName={}",fileName);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("originalFilename", originalFilename);
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("文件上传报错错误内容:{}",e.getMessage());
            return AjaxResult.error("文件上传报错错误内容{}",e.getMessage());
        }
    }

    /**
     * 多文件上传请求
     */
    @PostMapping("/common/uploads")
    public AjaxResult uploadFiles(MultipartFile[] files) throws Exception
    {
        try
        {
            // AjaxResult ajax = AjaxResult.error("上传失败");
            List dataList=new ArrayList();
            for (MultipartFile file : files) {
                Map<String,String> map=new HashMap<>();
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);   // 文件完整路径
                String url = serverConfig.getUrl() + fileName;              // 浏览器可以访问的url路径
                String originalFilename = file.getOriginalFilename();       // 文件的中文名
                System.out.println("fileName=="+fileName);
                map.put("fileName", fileName);
                map.put("url", url);
                map.put("originalFilename", originalFilename);
                dataList.add(map);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("data", dataList);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * WHOLESALE PERFORMANCE-recent 3 months O/S三方数据返回
     */
    @PostMapping(value = "/wprmos")
    public TableDataInfo wprmos(@RequestBody List<String> map){
        return getDataTable(annualReviewyService.listWprvo(map));
    }

    /**
     * 查年审提交后WHOLESALE PERFORMANCE-recent 3 months O/S的数据
     */
    @PostMapping(value = "/wprmosApproval")
    public TableDataInfo wprmosApproval(@RequestBody Map<String, Object> map){
        return getDataTable(annualReviewyService.listWprvoApproval(map));
    }

    /**
     * SALES PERFORMANCE AND TARGET 三方数据返回
     */
    @PostMapping(value = "/spat")
    public TableDataInfo spat(@RequestBody List<String> map){
        return getDataTable(annualReviewyService.listspat(map));
    }

    @PostMapping(value = "/spatApproval")
    public TableDataInfo spatApproval(@RequestBody Map<String, Object> map){

        return getDataTable(annualReviewyService.listspatApproval(map));
    }

    /**
     * （根据dealerName查sector，然后通过sector查sectorInformation）
     * LIMIT CALCULATION FOR COMMERCIAL NEEDS 数据返回
     */
    @PostMapping(value = "/lcfcn")
    public TableDataInfo lcfcn(@RequestBody List<String> map){

        return getDataTable(annualReviewyService.sectorinformationAndDealerinformation(map,null));
    }

    @PostMapping(value = "/addlcfcn")
    public AjaxResult addlcfcn(@RequestBody Map<String, Object> map){
        Map<String, Object> stringObjectMap = annualReviewyService.sectorinformationAndDealerinformation1(map);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", stringObjectMap);
        return ajax;
    }

    /**
     *
     * 查年审提交后LIMIT CALCULATION FOR COMMERCIAL NEEDS 的数据
     */
    @PostMapping(value = "/lcfcnApproval")
    public TableDataInfo lcfcnApproval(@RequestBody Map<String, Object> map){

        return getDataTable(annualReviewyService.approvalLimitCalculationForCommericalNeeds(map));
    }

    /**
     * （根据dealerName查plm表）
     * STOCK AUDIT PERFORMANCE(FOR RECENT 6 MONTHS)数据返回
     *
     */
    @ApiOperation("STOCK AUDIT PERFORMANCE(FOR RECENT 6 MONTHS)数据展示")
    @PostMapping(value = "/sapForRecent")
    public TableDataInfo sapForRecent(@RequestBody List<String> map){

        return getDataTable(annualReviewyService.selectplmWhereDealerName(map));
    }

//    @ApiOperation("年审信息临时保存")
//    @PostMapping("yearAuditSave")
//    public AjaxResult yearAuditSave(@RequestBody YearAuditSaveDTO yearAuditSaveDTO){
//        return annualReviewyService.yearAuditSave(yearAuditSaveDTO);
//    }

//    @ApiOperation("待办审核时临时保存note")
//    @PostMapping("waitForSave")
//    public AjaxResult waitForSave(@RequestBody WaitForSaveNoteDTO waitForSaveNoteDTO){
//        return annualReviewyService.waitForSaveNote(waitForSaveNoteDTO);
//    }

    @ApiOperation("草稿箱列表")
    @GetMapping("waitForDoList")
    public TableDataInfo waitForDoList(AnnualReviewy annualReviewy){
        startPage();
        List<AnnualReviewy> list = annualReviewyService.listMineDo();
        return getDataTable(list);
    }

    @ApiOperation("催办")
    @PostMapping("reminder")
    public AjaxResult reminder(@RequestBody AnnualReviewy annualReviewy){
        return annualReviewyService.reminder(annualReviewy.getInstanceId());
    }

    //TODO 待秉文提供接口
    @ApiOperation("合同文件刷新")
    @GetMapping("/contract/refresh")
    public AjaxResult refresh(@RequestBody AnnualReviewy annualReviewy){
        return annualReviewyService.reminder(annualReviewy.getInstanceId());
    }

    @PostMapping(value = "/annualReviewyInfo/{instanceId}")
    public AjaxResult annualReviewyInfo(@PathVariable("instanceId") String instanceId) {
        return AjaxResult.success(annualReviewyService.selectAnnualReviewyinfo(instanceId));

    }

    @GetMapping(value = "/getWorkName")
    public AjaxResult getWorkName() {
        return AjaxResult.success(annualReviewyService.getWorkName());

    }
    @GetMapping(value = "/getpostInfo")
    public AjaxResult getpostInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<String> strings = postService.selectPostListByUserId1(loginUser.getUser().getUserId());
        return AjaxResult.success(strings);

    }

    /**
     * 查询feikeDM提交流程列表
     */
    // @PreAuthorize("@ss.hasPermi('feike:feike:list')")
    @GetMapping("/listDm")
    public TableDataInfo listDm(AnnualReviewy annualReviewy) {
        startPage();
        List<ApprovalStatusVO> list = annualReviewyService.selectAnnualReviewyVODMList(annualReviewy);
        return getDataTable(list);
    }

    @PostMapping(value = "/fileZip/{instanceId}")
    public AjaxResult fileZip(@PathVariable("instanceId") String instanceId) {
        return AjaxResult.success(annualReviewyService.fileZip(instanceId));

    }

    @GetMapping(value = "/getAmlInfo/{instanceId}")
    public AjaxResult getAmlInfo(@PathVariable("instanceId") String instanceId) {
        Map<String, Object> map = new HashMap<>();  //一级
        Map<String, Object> data = new HashMap<>();  // 二级
        List<HAml>  amls = null;
        if(!StringUtils.isEmpty(instanceId)){
            String id = instanceId.replace("\"", "");
                HAml hAml = new HAml();
                hAml.setInstanceId(instanceId);
                amls = amlMapper.selectHAmlList(hAml);
                if(amls == null ||  amls.size() == 0){
                    amlMapper.insertAmlHis(hAml);
                    amls = annualReviewyService.selectAmlInfoList(id);
                }else{
                    if(amls.get(0).getName()!=null){
                        //说明已经结束了
                    }else{
                        amls = annualReviewyService.selectAmlInfoList(id);
                    }
                }
            ArrayList<String> arrayList = new ArrayList<>();
            for (HAml aml : amls) {
                arrayList.add(aml.getDealerName());
            }
            if(arrayList.size()>0){
                LinkedHashSet<String> set = new LinkedHashSet<>(arrayList);
                data.put("dealers",set);
            }
            data.put("aml",amls);
            map.put("data",data);
            return AjaxResult.success(map);
        }else{
            return AjaxResult.success();
        }
    }

    @PostMapping("/getCorporateGuaranteeInfo")
    public AjaxResult getCorporateGuaranteeInfo(@RequestBody Map<String, Object> map){
        ArrayList<HBasicCorporateGuarantee> GuaranteeList = new ArrayList<>();
        ArrayList<HBasicCorporate> CorporateList = new ArrayList<>();
        List dealerNameList = (List) map.get("dealerName");
        System.out.println("dealerNameList=="+dealerNameList);
        if(dealerNameList.size()>0){
            for (Object D : dealerNameList) {
                List<HBasicCorporateGuarantee> hBasicCorporateGuarantees = basicCorporateGuaranteeMapper.selectCorporateGuaranteeByName((String) D);
                if(hBasicCorporateGuarantees!=null && hBasicCorporateGuarantees.size()>0){
                    for (HBasicCorporateGuarantee hBasicCorporateGuarantee : hBasicCorporateGuarantees) {
                        GuaranteeList.add(hBasicCorporateGuarantee);
                    }
                }else{
                    HBasicCorporateGuarantee hBasicCorporateGuarantee1 = new HBasicCorporateGuarantee();
                    hBasicCorporateGuarantee1.setDealername((String) D);
                    hBasicCorporateGuarantee1.setGuarantorindustry(" ");
                    hBasicCorporateGuarantee1.setGuarantorregioncode(" ");
                    hBasicCorporateGuarantee1.setGuarantorscale(" ");
                    GuaranteeList.add(hBasicCorporateGuarantee1);
                }
                List<HBasicCorporate> hBasicCorporates = basicCorporateMapper.selectCorporateByName((String) D);
                if(hBasicCorporates!=null && hBasicCorporates.size()>0){
                    for (HBasicCorporate hBasicCorporate : hBasicCorporates) {
                        CorporateList.add(hBasicCorporate);
                    }
                }else{
                    HBasicCorporate hBasicCorporate1 = new HBasicCorporate();
                    hBasicCorporate1.setDealername((String) D);
                    hBasicCorporate1.setProvince(" ");
                    hBasicCorporate1.setCity(" ");
                    hBasicCorporate1.setPeoplesum(" ");
                    hBasicCorporate1.setDownloanaccount(" ");
                    hBasicCorporate1.setEnterprisetype(" ");
                    CorporateList.add(hBasicCorporate1);
                }
            }
        }
        HashMap<String, Object> respList = new HashMap<>();
        respList.put("GuaranteeInfo",GuaranteeList);
        respList.put("CorporateInfo",CorporateList);
        return AjaxResult.success(respList);
    }
}
